#!/bin/sh

set -e

. $(dirname $0)/Config.sh
. $(dirname $0)/utils.sh

error=

cleanup()
{
  echo "restoring fan settings"
  restorefanstate_gfrg200
}

fantest_gfrg200()
{
  run savefanstate_gfrg200

  run enabletach_gfrg200

  #  set freq to 23 (360khz / (2*23) = 7.8khz pulse?)
  #  or set freq to 9 (360khz / (2*9) = 10khz pulse?)
  freq=23

  # look for values within 15% of what is expected
  range=$(($fan_max_rpm * 15 / 100))

  run setfanfreq_gfrg200_i2c $freq

  # turn off fan
  run setfanrpm_gfrg200_sys 0		# 0% speed
  echo "fan at 0%"
  sleep 3			# why not, I'm thinking
  rpm=$(getfanrpm_gfrg200_i2c)
  echo RPM at 0% is $rpm
  if ! near 0 $range $rpm; then
    error="wanted 0 rpm, got $rpm for 0% duty cycle"
    cleanup
    return 1
  fi

  # write with /sys interface, check with i2cget
  run setfanrpm_gfrg200_sys 255		# 100% speed
  val=$(getfanspeed_gfrg200_i2c)
  want=$(speedtopercent_gfrg200_i2c $val)
  if [ $val != $want ]; then
    error="wanted $want, got $val for 100% duty cycle"
    cleanup
    return 1
  fi
  echo "fan at 100%"
  sleep 3
  rpm=$(getfanrpm_gfrg200_i2c)
  rpmsave=$rpm
  echo RPM at 100% is $rpm
  if ! near $fan_max_rpm $range $rpm; then
    error="wanted $fan_max_rpm rpm, got $rpm for 100% duty cycle"
    cleanup
    return 1
  fi

  # write with i2cset, verify with pwm1
  run setfanrpm_gfrg200_i2c 50			# 50%
  val=$(getfanrpm_gfrg200_sys)
  if [ $val != 128 ]; then
    error="wanted 128, got $val for 50% duty cycle"
    cleanup
    return 1
  fi
  echo "fan at 50%"
  sleep 3
  want=$(($fan_max_rpm / 2))
  rpm=$(getfanrpm_gfrg200_i2c)
  echo RPM at 50% is $rpm
  if ! near $want $range $rpm; then
    error="wanted $want rpm, got $rpm for 50% duty cycle"
    cleanup
    return 1
  fi

  # check temp sensors
  t1=$(gettemp_gfrg200 1)
  echo t1 is $t1
  if [ $t1 -lt $fan_temp1_min ] || [ $t1 -gt $fan_temp1_max ]; then
    error="wanted $fan_temp1_min-$fan_temp1_max, got $t1 for temp1_input"
    cleanup
    return 1
  fi
  t2=$(gettemp_gfrg200 2)
  echo t2 is $t2
  if [ $t2 -lt $fan_temp2_min ] || [ $t2 -gt $fan_temp2_max ]; then
    error="wanted $fan_temp2_min-$fan_temp2_max, got $t2 for temp2_input"
    cleanup
    return 1
  fi

  result="rpm=$rpmsave t1=$t1 t2=$t2"

  cleanup

  return 0
}

case "$1" in
  diag | quick)
    if fantest_gfrg200; then
      echo PASS "$result"
    else
      echo FAIL "$error"
    fi
    ;;
  *)
    echo "Usage: $0 {diag|quick}"
    exit 1
esac
